package br.ufu.wcm.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;

public class GenericDaoHibernateImpl<T, PK extends Serializable> implements
		GenericDao<T, PK> {
	
	protected Session session;
	protected Class<T> clazz;
	
	public GenericDaoHibernateImpl(Session session, Class<T> clazz) {
		this.session = session;
		this.clazz = clazz;
	}

	@SuppressWarnings("unchecked")
	@Override
	public PK salvar(T newInstance) {
		return (PK) session.save(newInstance);
	}

	@SuppressWarnings("unchecked")
	@Override
	public T get(PK id) {
		return (T) session.get(clazz, id);
	}

	@Override
	public void atualizar(T objetoTransiente) {
		session.update(objetoTransiente);
	}

	@Override
	public void remover(T objetoPersistente) {
		session.delete(objetoPersistente);
	}
	
	@SuppressWarnings("unchecked")
	public List<T> buscarTodos() {
		Criteria criteria = session.createCriteria(clazz);
		return criteria.list();
	}
	
	@SuppressWarnings("unchecked")
	public List<T> buscarPorExemplo(T objeto) {
		Criteria criteria = session.createCriteria(clazz);
		Example example = Example.create(objeto).excludeZeroes().enableLike(MatchMode.ANYWHERE);
		criteria.add(example);
		
		return criteria.list();
	}

}
